package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.file.Path;
import java.util.*;

/**
 * 定义全局过滤器，会对所有路由生效
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
public class PreventFilter implements GlobalFilter, Ordered {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${prevent.time}")
    private String preventTime;

    @Value("${prevent.times}")
    private String preventTimes;

    private static HashMap ipMap = new HashMap();
    private static HashMap timeMap = new HashMap();

    static {
        ipMap.put("0:0:0:0:0:0:0:1", 0);
    }

    /**
     * 过滤器核心方法
     * @param exchange 封装了request和response对象的上下文
     * @param chain 网关过滤器链（包含全局过滤器和单路由过滤器）
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 思路：获取客户端ip，判断是否在黑名单中，在的话就拒绝访问，不在的话就放行
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 从request对象中获取客户端ip
        String clientIp = request.getRemoteAddress().getHostString();

        String path = request.getPath().toString();
        // 防暴刷如果是请求注册接口，则进行请求次数的加1
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        if(path.contains("index")|| path.contains("isRegistered")||path.contains("/code/create")){ return chain.filter(exchange); }  //登录页放行


        if(path.contains("/user/register")) {
            // 决绝访问，返回
            // response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
            if(ipMap.get(clientIp)==null){
                ipMap.put(clientIp,1);
                timeMap.put(clientIp,new Date()) ;
            }else{
                ipMap.put(clientIp,(int)ipMap.get(clientIp)+1);
                timeMap.put(clientIp,new Date()) ;
            }
            if ((int)ipMap.get(clientIp) > Integer.parseInt(preventTimes)) {
                Date time=(Date)timeMap.get(clientIp) ;
                if((new Date()).getTime()-time.getTime()<60*Integer.parseInt(preventTime)){
                    String data = "You registered too much ! Request be denied!";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }else{
                    ipMap.put(clientIp,1);
                    timeMap.put(clientIp,new Date()) ;
                }

            }
            return chain.filter(exchange);
        }


        if (!cookies.isEmpty()){
            List<HttpCookie> token = cookies.get("token");
            if(token!=null && token.size() > 0){
                HttpCookie httpCookie = token.get(0);
                String cookieValue = httpCookie.getValue();
                System.out.println("======取到的cookievalue为：" + cookieValue);

                // 全局验证token
                String url = "http://lagou-service-user/user/info/" + cookieValue;
                String  responseCode = restTemplate.getForObject(url, String.class);

                if(!StringUtils.isEmpty(responseCode)){
                    String data = responseCode + "  welcome to the system";
                    DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                    return response.writeWith(Mono.just(wrap));
                }
            }
        }





        // 统一认证
        if ("/user/login".equals(path)) {
            // 验证用户名密码是否合法
            System.out.println("=====>>>用户名密码合法验证通过");

        }

        // 合法请求，放行，执行后续的过滤器
        return chain.filter(exchange);
    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
